<template>
	<div>
		<el-form :model="state.taskParam" :validate-on-rule-change="false" label-width="90px" :rules="state.isTestings?state.rules:{}" ref="ruleFormRef">
			<el-form-item label="审批结果" style="width: 100%;" prop="description">
				<el-radio-group v-model="state.taskParam.description">
					<el-radio label="1" value="1">同意</el-radio>
					<el-radio v-if="disagreeShow" label="4" value="4">不同意</el-radio>
					<el-radio v-if="state.retractRecordData.length > 0" label="0" value="0">退回</el-radio>
				</el-radio-group>
			</el-form-item>
				<el-form-item label="退回节点" v-if="state.retractDialogVisible && state.retractRecordData.length > 0" prop="retractNodeKey">
					<el-select v-model="state.retractNodeKey" placeholder="请选择" style="width:100%;">
						<el-option v-for="item in  state.retractRecordData" :key="item.taskKey" :label="item.taskName"
							:value="item.taskKey">
						</el-option>
					</el-select>
				</el-form-item>
			<el-form-item label="处理意见" style="width: 100%;" prop="approveAdvice">
				<el-input type="textarea" :rows="4" placeholder="请输入内容" maxlength="1000" show-word-limit
					v-model="state.taskParam.approveAdvice">
					<template #append>
						<el-button icon="ele-FolderChecked" v-if="tempSaveButtonShow" @click="saveApproveAdviceText"
							:loading="state.saveApproveAdviceLoaing">暂存</el-button>
					</template>
				</el-input>
			</el-form-item>
			<el-form-item label="流程附件">
				<FileUpload :businessId="taskId" style="width: 100%"></FileUpload>
			</el-form-item>
		</el-form>
		<div v-if="isFooterBtn" style="text-align:center">
			<el-button type="primary" @click="dataFormSubmit(ruleFormRef)">提交</el-button>
			<el-button type="primary" @click="doClose">关闭</el-button>
			<el-button v-if="isStopFooterBtn" type="primary" @click="stopProcess">终止</el-button>
		</div>
		<el-dialog title="终止原因" v-model="state.stopVisible">
			<el-form>
				<el-form-item label="终止原因">
					<el-input v-model="state.stopReason" placeholder="请输入终止原因"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="doStopProcess">确定</el-button>
				<el-button type="primary" @click="state.stopVisible =false">关闭</el-button>
			</span>
		</el-dialog>
	</div>
</template>
<script setup lang="ts" name="approveCommonFoot">
import { ElLoading, ElMessage, FormInstance } from 'element-plus';
import { defineAsyncComponent, onMounted, reactive, ref, watch } from 'vue';
import { TaskParam, TaskVo, workflowApi } from '/@/api/sys/workflow-api';

const FileUpload = defineAsyncComponent(() => import('/@/components/fileUpload/index.vue'))

const props = defineProps({
	modelValue: {
		type: Object,
		required: true
	},
	taskId: {
		type: String,
		required: true
	},
	processId: {
		type: String,
		required: true
	},
	businessKey: {
		type: String,
		required: true
	},
	isUpload: {
		type: Boolean,
		default: true
	},
	disagreeShow: {
		type: Boolean,
		default: false
	},
	authCategory: {
		type: String,
		default: '0'
	},
	owner: {
		type: String,
		default: ''
	},
	tempSaveButtonShow: {
		type: Boolean,
		default: false
	},
	//是否展示底部流程处理按钮
	isFooterBtn: {
		type: Boolean,
		default: true
	},
	//是否展示终止按钮
	isStopFooterBtn: {
		type: Boolean,
		default: false
	},
	//业务自定义终止方法，父组件实现customStopProcess方法
	isCustomStop: {
		type: Boolean,
		default: false,
	}
})
const ruleFormRef = ref<FormInstance>()
const emit = defineEmits(['update:modelValue', 'refreshEmit', 'dataFormSubmit', 'customStopProcess'])
const state = reactive({
	isTestings: true,
	taskParam: {
		taskId: '',
		processId: '',
		defKey: '',
		businessKey: '',
		tenantId: '',
		description: '',
		userId: '',
		approveAdvice: '',
		approveUserId: '',
		briefReport: '',
		skipFirstNode: '',
		processVariables: {},
		taskVariables: {},
		formProperties: {},
		businessDesignerId: '',
		businessDesignerCode: '',
		owner: '',
		authCategory: '',
	} as TaskParam,
	retractDialogVisible: false,
	retractRecordData: [] as TaskVo[],
	selectReatracNode: {} as TaskVo,
	retractNodeKey: '',
	saveApproveAdviceLoaing: false,
	rules: {
		description: [
			{ required: true, message: '请选择审批结果', trigger: 'blur' }
		],
		approveAdvice: [
			{ required: true, message: '请填写意见', trigger: 'blur' }
		],
		retractNodeKey:{required: false, message: '请选择要退回的节点', trigger: 'blur'}
	},
	stopVisible: false,
	stopReason: '',
})
// 页面加载时
onMounted(() => {
	ruleFormRef.value?.resetFields()
	state.taskParam.taskId = props.taskId
	state.taskParam.businessKey = props.businessKey
	state.taskParam.authCategory = props.authCategory
	state.taskParam.owner = props.owner
	state.taskParam.processId = props.processId
	state.taskParam.description = '1'
	initRetractNodes()
})

// 初始化可退回节点
const initRetractNodes = () => {
	state.retractRecordData = []
	workflowApi.getRetractNodeByTaskId(props.taskId).then((data) => {
		if (data.code === 0) {
			state.retractRecordData = data.data
			if (state.retractRecordData.length === 1) {
				state.selectReatracNode = state.retractRecordData[0]
				state.retractNodeKey = state.retractRecordData[0].taskKey
			} else if (state.retractRecordData.length === 0) {
				state.selectReatracNode = {} as TaskVo
			}
		}
	}).catch(() => {
	})
}
watch(() => state.taskParam.description, (val:string) => {
	if (val == '0') {
		state.retractDialogVisible = true
		state.rules.retractNodeKey.required = true
		state.taskParam.approveAdvice = '退回'
	}else if(val == '1'){
		state.retractDialogVisible = false
		state.rules.retractNodeKey.required = false
		state.taskParam.approveAdvice = '同意'
	}else if(val == '4'){
		state.retractDialogVisible = false
		state.rules.retractNodeKey.required = false
		state.taskParam.approveAdvice = '不同意'
	}else{
		// 啥也不做
	}
})
// 暂存审批意见
const saveApproveAdviceText = () => {

}
//关闭按钮
const doClose = () => {
	emit('refreshEmit')
}
//终止流程
const stopProcess = () => {
	state.stopReason = ''
	state.stopVisible = true
}
const doStopProcess = () => {
	if(props.isCustomStop){
		emit('customStopProcess')
	}else{
		 //提交数据
		const loading = ElLoading.service({
			lock: true,
			text: '处理中',
			background: 'rgba(0, 0, 0, 0.7)',
		})
		workflowApi.deleteProcess(props.processId, state.stopReason).then((data) => {
			if(data.code === 0){
				ElMessage.success('流程终止成功')
			}else{
				ElMessage.error(data.message)
			}
		}).catch(() => {
			ElMessage.error('流程终止失败')
		}).finally(() => {
			loading.close()
		})
	}
}
//提交流程
const dataFormSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.validate((valid: boolean) => {
		if (valid) {
			if (state.taskParam.description !== '0') {
				//交由业务功能自己提交流程
				emit('dataFormSubmit', state.taskParam)
			} else {
				const loading = ElLoading.service({
					lock: true,
					text: '处理中',
					background: 'rgba(0, 0, 0, 0.7)',
				})
				//退回流程
				workflowApi.submitRetract({
					'taskId': state.taskParam.taskId,
					'retractNodeKey': state.retractNodeKey,
					'userId': state.selectReatracNode.assignee,
					'approveAdvice': state.taskParam.approveAdvice,
					'description': state.taskParam.description
				}).then((data) => {
					if (data.code === 0) {
						ElMessage.success('退回流程成功')
						emit('refreshEmit')
					} else {
						ElMessage.error(data.message)
					}
				}).catch(() => {
					ElMessage.error('退回流程失败')
				}).finally(() => {
					loading.close()
				})
			}
			
		}
	})
}
</script>